/**
 * 使用内置的 El-Popover 控制台会报错，因此自己封装一个来实现相同功能
 */

type IPopoverList = Array<{
  title: string;
  shortcut?: string;
  callback: () => void;
}>;

export class Popover {
  private popover: HTMLElement;
  private mask: HTMLElement;
  private menuList: IPopoverList;

  constructor(menuList: IPopoverList) {
    this.menuList = menuList;
    // 先创建 mask
    this.mask = document.createElement("div");
    this.mask.classList.add("unicode-mask-box");
    document.body.appendChild(this.mask);

    // 后创建 菜单
    this.popover = document.createElement("div");
    this.popover.classList.add("unicode-popover");

    // 循环创建子项
    for (let i = 0; i < this.menuList.length; i++) {
      const item = this.menuList[i];
      const menuItem = document.createElement("div");
      menuItem.classList.add("unicode-popover-item");
      // 内部创建
      menuItem.innerHTML = `<span class="text">${
        item.title
      }</span> <span class="shortcut">${item.shortcut || ""}</span>`;
      menuItem.addEventListener("click", item.callback);
      this.popover.appendChild(menuItem);
    }

    // 添加到 mask
    this.mask.appendChild(this.popover);

    // 处理事件
    this.mask.addEventListener("click", this.close.bind(this));
    this.mask.addEventListener("popover", (e) => e.preventDefault());
  }

  public show(payload: {
    x: number;
    y: number;
    hiddenMask?: boolean;
    width?: number;
    offsetX?: number;
    offsetY?: number;
  }) {
    const {
      x,
      y,
      hiddenMask = false,
      width = 220,
      offsetX = 0,
      offsetY = 0,
    } = payload;

    this.mask.style.display = "block";
    if (hiddenMask) this.mask.style.backgroundColor = "transparent";
    // transform 实现定位
    this.popover.style.transform = `translate(${x + offsetX}px, ${
      y + offsetY
    }px)`;

    if (width) this.popover.style.width = `${width}px`;
  }
  public close() {
    this.mask.style.display = "none";
    this.popover.style.transform = `translate(0)`;
  }
}
